package com.xxrl.shop.service;

import com.xxrl.shop.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.util.Pair;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;
import java.util.UUID;

/**
 * @author mis
 */
@Service
public class FileService {
    private static final Logger logger = LoggerFactory.getLogger(FileService.class);

    private static final String[] IMAGE_TYPE = {"png","jpeg","jpg", "png", "bmp"};

    @Value("${my.images.path}")
    private String imagePath;

    @Value("${my.images.host}")
    private String imageHost;


    private void saveImgToFile(String fileName,byte[] fileData) throws IOException {
        try (OutputStream out = new FileOutputStream(new File(imagePath,fileName))){
            out.write(fileData);
            out.flush();
        }
    }
    public Pair<String,Boolean> saveImg(MultipartFile uploadFile) {
        StringBuilder fileName = new StringBuilder();
        fileName.append(UUID.randomUUID().toString().replaceAll("-", ""));
        if (uploadFile == null || uploadFile.isEmpty()) {
            return Pair.of("图片缺失",false);
        }
        logger.info("Upload file {}",fileName);
        try {
            saveImgToFile(fileName.toString(),uploadFile.getBytes());
        } catch (IOException e) {
            logger.warn("Upload file fail for {}",e.getMessage());
            return Pair.of("保存失败",false);
        }
        return Pair.of(imageHost+fileName,true);
    }

    public Pair<String,Boolean> saveBase64(String base64Str) {
        StringBuilder fileName = new StringBuilder();
        fileName.append(UUID.randomUUID().toString().replaceAll("-", "")).append('.');
        if (StringUtils.isEmpty(base64Str)) {
            return Pair.of("图片缺失",false);
        }
        boolean ok = false;
        for (String type : IMAGE_TYPE) {
            String contain = String.format("data:image/%s;base64,",type);
            if (base64Str.contains(contain)) {
                base64Str = base64Str.replace(contain,"");
                fileName.append(type);
                ok = true;
                break;
            }
        }
        if (!ok) {
            return Pair.of("格式不支持",false);
        }
        logger.info("Upload file {}",fileName);
        try {
            saveImgToFile(fileName.toString(),Base64.getDecoder().decode(base64Str));
        } catch (IOException e) {
            logger.warn("Upload file fail for {}",e.getMessage());
            return Pair.of("保存失败",false);
        }
        return Pair.of(imageHost+fileName,true);
    }

}
